package com.zys.sac.uc.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zys.sac.core.config.UrlFilterInvocationSecurityMetadataSource;
import com.zys.sac.core.entity.SacPermission;
import com.zys.sac.core.entity.SacRole;
import com.zys.sac.uc.entity.SacResource;
import com.zys.sac.uc.entity.SacRoleResource;
import com.zys.sac.uc.service.ISacResourceService;
import com.zys.sac.uc.service.ISacRoleResourceService;
import com.zys.sac.uc.vo.ResourceInfoVO;
import com.zys.sac.uc.vo.RoleInfoVO;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: haize
 * @Date: 2022/08/26/18:01
 * @Description:
 */
@Component
public class UcUrlFilterInvocationSecurityMetadataSource extends UrlFilterInvocationSecurityMetadataSource {

    @Resource
    private ISacRoleResourceService sacRoleResourceService;

    @Resource
    private ISacResourceService sacResourceService;

    @Override
    protected SacPermission findPermissionByUrl(String url) {
        LambdaQueryWrapper<SacResource> query = new LambdaQueryWrapper<>();
        query.eq(SacResource::getUri, url);
        List<SacResource> resources = sacResourceService.list(query);
        Assert.isTrue(resources.size() <= 1, "路由url重复");
        return resources.size() == 1 ? new ResourceInfoVO(resources.get(0).getCode()) : null;
    }

    @Override
    protected List<? extends SacRole> findPermissionRole(String permissionCode) {
        LambdaQueryWrapper<SacRoleResource> query = new LambdaQueryWrapper<>();
        query.eq(SacRoleResource::getResourceCode, permissionCode);
        List<SacRoleResource> byResCode = sacRoleResourceService.list(query);
        return byResCode.stream().map(o -> new RoleInfoVO(o.getRoleCode())).collect(Collectors.toList());
    }
}
